package com.mypack.student.controller.achievement;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.PageInfo;
import com.mypack.student.constants.EnumDeleteFlag;
import com.mypack.student.constants.EnumResponse;
import com.mypack.student.context.SessionContext;
import com.mypack.student.dto.achievement.StudentAchievementDTO;
import com.mypack.student.dto.achievement.StudentAchievementExportDTO;
import com.mypack.student.dto.achievement.StudentAchievementSearchDTO;
import com.mypack.student.service.account.auth.AccountAuthService;
import com.mypack.student.service.achievement.StudentAchievementService;
import com.mypack.student.utils.Result;
import com.mypack.student.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/student/achievement")
@Slf4j
public class StudentAchievementController {

    @Autowired
    private StudentAchievementService studentAchievementService;
    @Autowired
    private AccountAuthService accountAuthService;
    @Autowired
    private MapperFacade mapperFacade;

    @RequestMapping("/list")
    public Result list(@RequestBody StudentAchievementSearchDTO searchDTO) {

        searchDTO.setClazzIdList(accountAuthService.queryClazzIdByAccountId(SessionContext.getAccountId()));

        List<StudentAchievementDTO> studentAchievementDTOList = studentAchievementService.list(searchDTO, true);

        return ResultUtils.success(new PageInfo<>(studentAchievementDTOList));


    }

    @RequestMapping("/add")
    public Result add(@RequestBody StudentAchievementDTO studentAchievementDTO) {

        studentAchievementService.add(studentAchievementDTO);

        return ResultUtils.success();


    }

    @RequestMapping("/update")
    public Result update(@RequestBody StudentAchievementDTO studentAchievementDTO) {

        studentAchievementService.update(studentAchievementDTO);

        return ResultUtils.success();


    }

    @RequestMapping("/delete")
    public Result delete(Integer id) {

        if (id == null) {
            return ResultUtils.fail(EnumResponse.INVALID_PARAM);
        }

        StudentAchievementDTO studentAchievementDTO = new StudentAchievementDTO();
        studentAchievementDTO.setId(id);
        studentAchievementDTO.setDeleteFlag(EnumDeleteFlag.YES.getCode());

        studentAchievementService.update(studentAchievementDTO);

        return ResultUtils.success();

    }

    @GetMapping("/export")
    public void export(StudentAchievementSearchDTO searchDTO, HttpServletResponse response) {


        List<StudentAchievementDTO> studentAchievementDTOList = studentAchievementService.list(searchDTO, true);

        if (CollectionUtils.isEmpty(studentAchievementDTOList)) {
            return;
        }

        List<StudentAchievementExportDTO> studentAchievementExportDTOS = mapperFacade.mapAsList(studentAchievementDTOList, StudentAchievementExportDTO.class);

        // 算总分
        studentAchievementExportDTOS.forEach(item -> item.setTotalScore(item.getChinese().add(item.getMath()).add(item.getEnglish())));

        // 降序排列
        List<StudentAchievementExportDTO> sortList = studentAchievementExportDTOS.stream().sorted(Comparator.comparing(StudentAchievementExportDTO::getTotalScore).reversed()).collect(Collectors.toList());


        ExcelWriter excelWriter = null;
        try {
            String fileName = URLEncoder.encode("学生成绩信息", "utf-8").replaceAll("\\+", "%20") + ".xlsx";
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
            // 这里 指定文件
            excelWriter = EasyExcel.write(response.getOutputStream(), StudentAchievementExportDTO.class).build();
            // 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。StudentExportDTO.class 可以每次都变，我这里为了方便 所以用的同一个class 实际上可以一直变
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "学生成绩信息").build();
            // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
            excelWriter.write(sortList, writeSheet);
        } catch (Exception e) {
            log.error("导出学生成绩信息异常", e);
        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }


}
